package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;

    //套餐删除
    @Override
    @Transactional
    public void delete1(List<Long> ids) {
        //查询套餐销售状态
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId, ids);
        lqw.eq(Setmeal::getStatus, 1);
        Integer integer = setmealMapper.selectCount(lqw);
        if (integer > 0) {
            throw new CustomException("套餐正在售卖中。。。。不能删除");
        }
        //    如果可以，删除套餐
        for (Long id : ids) {
            setmealMapper.deleteById(id);
        }
        //查询关联菜品
        LambdaQueryWrapper<SetmealDish> lqw1 = new LambdaQueryWrapper<>();
        lqw1.in(SetmealDish::getSetmealId, ids);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(lqw1);
        for (SetmealDish setmealDish : setmealDishes) {
            Long id = setmealDish.getId();
            setmealDishMapper.deleteById(id);
        }

    }

    //更新套餐
    @Override
    public void updateSetema(SetmealDto setmealDto) {
        //取出套餐id
        Long id = setmealDto.getId();
        //更新套餐
        setmealMapper.updateById(setmealDto);
        //取出关联的菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //删除原先的
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes1 = setmealDishMapper.selectList(lqw);
        if(setmealDishes1!=null){
            for (SetmealDish setmealDish : setmealDishes1) {
                Long id1 = setmealDish.getId();
                setmealDishMapper.deleteById(id1);
            }
        }
        //添加修改的菜品
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(id);
            setmealDishMapper.insert(setmealDish);
        }
    }
}
